﻿using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpenCvApplication.View
{
    public partial class FrmReducedResolution : FrmBase
    {
        public FrmReducedResolution()
        {
            InitializeComponent();
        }
        private string _filePath;
        /// <summary>
        /// 选择图像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            var filePath = SelectFile(ImageExtension);
            if (string.IsNullOrEmpty(filePath)) return;

            _filePath = filePath;
            if (this.pictureBox1.Image != null)
                this.pictureBox1.Image.Dispose();
            this.pictureBox1.Image = Image.FromFile(filePath);
            label1.Text = GetImageSize(this.pictureBox1.Image, _filePath);
        }
        public string GetImageSize(Image image, string filePath)
        {
            // 获取图像的物理尺寸
            SizeF imageSize = image.PhysicalDimension;
            // 获取图像文件的大小
            FileInfo fileInfo = new FileInfo(filePath);
            long fileSize = fileInfo.Length;

            // 计算图像的大小（以字节为单位）
            //long imageSizeInBytes = CalculateImageSize(image);

            // 根据文件大小选择合适的单位
            string sizeString;
            if (fileSize >= 1024 * 1024)
            {
                sizeString = $"{(fileSize / (1024f * 1024f)):0.##} MB";
            }
            else
            {
                sizeString = $"{(fileSize / 1024f):0.##} KB";
            }

            return $"分辨率：{imageSize.Width} x {imageSize.Height}；大小：{sizeString}";
        }
        public Image ReduceImageResolution(string sourceImagePath, string targetImagePath, int targetWidth, int targetHeight)
        {
            using (Image sourceImage = Image.FromFile(sourceImagePath))
            {
                // 创建目标图像
                using (Bitmap targetImage = new Bitmap(targetWidth, targetHeight))
                {
                    // 设置目标图像的分辨率
                    targetImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

                    using (Graphics graphics = Graphics.FromImage(targetImage))
                    {
                        // 设置绘图质量
                        graphics.CompositingQuality = CompositingQuality.HighQuality;
                        graphics.SmoothingMode = SmoothingMode.HighQuality;
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        // 绘制缩小后的图像
                        graphics.DrawImage(sourceImage, 0, 0, targetWidth, targetHeight);
                    }

                    // 保存目标图像
                    targetImage.Save(targetImagePath);

                    return targetImage;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            string path = Path.GetDirectoryName(_filePath);
            string filePath = Path.Combine(path, "Test" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".jpg");
            if (pictureBox2.Image != null)
                pictureBox2.Image.Dispose();
            //pictureBox2.Image = ResizeImageByScale(this.pictureBox1.Image, (double)numericUpDown2.Value);
            CompressImage(_filePath, filePath, (int)numericUpDown2.Value);
            //pictureBox2.Image.Save(filePath);
            //label2.Text = GetImageSize(this.pictureBox2.Image, filePath);
        }
        public Image ResizeImageByScale(Image image, double scale)
        {
            int newWidth = (int)(image.Width * scale);
            int newHeight = (int)(image.Height * scale);

            Bitmap resizedImage = new Bitmap(newWidth, newHeight);
            using (Graphics graphics = Graphics.FromImage(resizedImage))
            {
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
            }

            return resizedImage;
        }
        public Image ResizeImageProportionally(Image image, int targetSize)
        {
            int originalWidth = image.Width;
            int originalHeight = image.Height;

            float ratio = (float)targetSize / Math.Max(originalWidth, originalHeight);
            int newWidth = (int)(originalWidth * ratio);
            int newHeight = (int)(originalHeight * ratio);

            Bitmap resizedImage = new Bitmap(newWidth, newHeight);
            using (Graphics graphics = Graphics.FromImage(resizedImage))
            {
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);
            }

            return resizedImage;
        }





        public void CompressImage(string sourceImagePath, string destinationImagePath, int targetSizeInKb)
        {
            using (Image<Bgr, byte> sourceImage = new Image<Bgr, byte>(sourceImagePath))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    // 将图像保存到内存流中
                    sourceImage.Bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                    long sourceSizeInBytes = memoryStream.Length;
                    int targetSizeInBytes = targetSizeInKb * 1024;

                    // 如果源图像已经在目标大小范围内，则直接保存并返回
                    if (sourceSizeInBytes <= targetSizeInBytes)
                    {
                        sourceImage.Save(destinationImagePath);
                        return;
                    }

                    // 计算压缩比例
                    double compressionRatio = (double)targetSizeInBytes / sourceSizeInBytes;

                    // 创建压缩后的图像
                    int targetWidth = (int)(sourceImage.Width * Math.Sqrt(compressionRatio));
                    int targetHeight = (int)(sourceImage.Height * Math.Sqrt(compressionRatio));
                    Image<Bgr, byte> compressedImage = sourceImage.Resize(targetWidth, targetHeight, Inter.Cubic);

                    // 保存压缩后的图像
                    compressedImage.Save(destinationImagePath);
                }
            }
        }
    }
}
